package com.glodon.paas.search.util;

import javax.annotation.PostConstruct;

import org.apache.commons.lang.StringUtils;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class ElasticSearchUtils {

    @Value("${search.es.address:localhost:9300}")
    private String esUrl;
    private InetSocketTransportAddress[] addresses;

    @PostConstruct
    public void init() {
        if (StringUtils.isNotEmpty(esUrl)) {
            String[] address = StringUtils.split(esUrl, ",");
            addresses = new InetSocketTransportAddress[address.length];
            for (int i = 0; i < address.length; i++) {
                String[] hostPort = StringUtils.split(address[i], ":");
                String host = hostPort[0];
                int port = Integer.parseInt(hostPort[1]);
                addresses[i] = new InetSocketTransportAddress(host, port);
            }
        }
    }

    /**
     * 获取到elasticsearch的连接client.
     * 
     * @return
     */
    public Client getClient() {
        return new TransportClient().addTransportAddresses(addresses);
    }

    public void closeClient(Client client) {
        if (client != null) {
            client.close();
        }
    }
}
